/*export const xx ={
  install(Vue){
    Vue.directive('xx',{
      bind(el,bind){
        el.addEventListener('click',()=>{
          console.log("nihao ")
        })
      },
      inserted(el, binding,vNode){

      },
      // 所在组件的 VNode 更新时调用，但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变，也可能没有
      update(el, binding,vNode){

      },
      // 解绑时
      unbind(el, binding,vNode){

      }
    })
  },
}*/
/*全局自定义指令的 汇总*/

const Clipboard = require('clipboard')
if (!Clipboard) {
  throw new Error('you should npm install `clipboard` --save at first ')
}

export const xx = {
  /* install(Vue){
     Vue.directive('xx',{

     })
   },*/
  bind(el, bind) {
    el.addEventListener('click', () => {
      console.log("nihao ")
    })
  },
  inserted(el, binding, vNode) {

  },
  // 所在组件的 VNode 更新时调用，但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变，也可能没有
  update(el, binding, vNode) {

  },
  // 解绑时
  unbind(el, binding, vNode) {

  }
}

/**
 *  使用示例 复制文本
    <el-input v-model="inputData" placeholder="Please input" style="width:400px;max-width:100%;"/>
    <el-button v-clipboard:copy="inputData" v-clipboard:success="clipboardSuccess" type="primary" icon="el-icon-document">  </el-button>
    clipboardSuccess  自定义一个方法
 * */
export const clipboard = {
  bind(el, binding) {
    if (binding.arg === 'success') {
      el._v_clipboard_success = binding.value
    } else if (binding.arg === 'error') {
      el._v_clipboard_error = binding.value
    } else {
      const clipboard = new Clipboard(el, {
        text() { return binding.value },
        action() { return binding.arg === 'cut' ? 'cut' : 'copy' }
      })
      clipboard.on('success', e => {
        const callback = el._v_clipboard_success
        callback && callback(e) // eslint-disable-line
      })
      clipboard.on('error', e => {
        const callback = el._v_clipboard_error
        callback && callback(e) // eslint-disable-line
      })
      el._v_clipboard = clipboard
    }
  },
  update(el, binding) {
    if (binding.arg === 'success') {
      el._v_clipboard_success = binding.value
    } else if (binding.arg === 'error') {
      el._v_clipboard_error = binding.value
    } else {
      el._v_clipboard.text = function() { return binding.value }
      el._v_clipboard.action = function() { return binding.arg === 'cut' ? 'cut' : 'copy' }
    }
  },
  unbind(el, binding) {
    if (binding.arg === 'success') {
      delete el._v_clipboard_success
    } else if (binding.arg === 'error') {
      delete el._v_clipboard_error
    } else {
      el._v_clipboard.destroy()
      delete el._v_clipboard
    }
  }
}


//自定义指令=> 文字复制
export const copy = {
  bind(el, binding) {
    // 双击触发复制
    if (binding.modifiers.dblclick) {
      el.addEventListener('dblclick', () => handleClick(el.innerText))
      el.style.cursor = 'copy'
    }
    // 点击icon触发复制
    else if (binding.modifiers.icon) {
      if (el.hasIcon) return
      const iconElement = document.createElement('i')
      iconElement.setAttribute('class', 'el-icon-document-copy')
      iconElement.setAttribute('style', 'margin-left:5px')
      el.appendChild(iconElement)
      el.hasIcon = true
      iconElement.addEventListener('click', () => handleClick(el.innerText))
      iconElement.style.cursor = 'copy'
    }
    // 单击触发复制
    else {
      el.addEventListener('click', () => handleClick(el.innerText))
      el.style.cursor = 'copy'
    }
  }
}
// v-copy 工具函数
function handleClick(text) {
  // 创建元素
  if (!document.getElementById('copyTarget')) {
    const copyTarget = document.createElement('input')
    copyTarget.setAttribute('style', 'position:fixed;top:0;left:0;opacity:0;z-index:-1000;')
    copyTarget.setAttribute('id', 'copyTarget')
    document.body.appendChild(copyTarget)
  }

  // 复制内容
  const input = document.getElementById('copyTarget')
  input.value = text
  input.select()
  document.execCommand('copy')
  console.log('复制成功')
}


// 自动聚焦
export const focus = {
  inserted(el, {value}) {
    if (value) el.focus()
  }
}

// 随机生成颜色
export const color = {
  bind(el, binding) {
    el.style.color ="#"+Math.random().toString(16).slice(2,8);
  }
}

/*元素的拖拽*/
export const draggable = {
    inserted(obj,binding){
      obj.onmousedown = function(event){
        obj.style.position = "absolute";
        obj.style.cursor = "move"
        obj.setCapture && obj.setCapture();
        event = event || window.event;
        var ol = event.clientX - obj.offsetLeft;
        var ot = event.clientY - obj.offsetTop;
        document.onmousemove = function(event){
          event = event || window.event;
          var left = event.clientX - ol;
          var top = event.clientY - ot;
          //修改box1的位置
          obj.style.left = left+"px";
          obj.style.top = top+"px";
        };
        //为document绑定一个鼠标松开事件
        document.onmouseup = function(){
          document.onmousemove = null;
          document.onmouseup = null;
          obj.releaseCapture && obj.releaseCapture();
        };
        return false;

      };
    }

}

/*el-dialog的拖拽*/
export const elDragDialog = {
  bind(el, binding, vnode) {
    const dialogHeaderEl = el.querySelector('.el-dialog__header')
    const dragDom = el.querySelector('.el-dialog')
    dialogHeaderEl.style.cssText += ';cursor:move;'
    dragDom.style.cssText += ';top:0px;'

    // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
    const getStyle = (function() {
      if (window.document.currentStyle) {
        return (dom, attr) => dom.currentStyle[attr]
      } else {
        return (dom, attr) => getComputedStyle(dom, false)[attr]
      }
    })()

    dialogHeaderEl.onmousedown = (e) => {
      // 鼠标按下，计算当前元素距离可视区的距离
      const disX = e.clientX - dialogHeaderEl.offsetLeft
      const disY = e.clientY - dialogHeaderEl.offsetTop

      const dragDomWidth = dragDom.offsetWidth
      const dragDomHeight = dragDom.offsetHeight

      const screenWidth = document.body.clientWidth
      const screenHeight = document.body.clientHeight

      const minDragDomLeft = dragDom.offsetLeft
      const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth

      const minDragDomTop = dragDom.offsetTop
      const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomHeight

      // 获取到的值带px 正则匹配替换
      let styL = getStyle(dragDom, 'left')
      let styT = getStyle(dragDom, 'top')

      if (styL.includes('%')) {
        styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100)
        styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100)
      } else {
        styL = +styL.replace(/\px/g, '')
        styT = +styT.replace(/\px/g, '')
      }

      document.onmousemove = function(e) {
        // 通过事件委托，计算移动的距离
        let left = e.clientX - disX
        let top = e.clientY - disY

        // 边界处理
        if (-(left) > minDragDomLeft) {
          left = -minDragDomLeft
        } else if (left > maxDragDomLeft) {
          left = maxDragDomLeft
        }

        if (-(top) > minDragDomTop) {
          top = -minDragDomTop
        } else if (top > maxDragDomTop) {
          top = maxDragDomTop
        }

        // 移动当前元素
        dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`

        // emit onDrag event
        vnode.child.$emit('dragDialog')
      }

      document.onmouseup = function(e) {
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
}

/*下拉加载更多*/
export const loadmore = {
  //只调用一次，指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置
  bind(el, binding, vNode) {
    //  selectors表示一个或多个匹配元素的 CSS 选择器
    const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
    SELECTWRAP_DOM.addEventListener('scroll', function () {
      /*
      * scrollHeight 获取元素内容高度(只读)
      * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
      * clientHeight 读取元素的可见高度(只读)
      * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
      * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
      */

      // 这个 + 1 有妙用
      // 滚动区域总高度 - 滚动了多少 <= 可视区域
      // console.log(this.scrollHeight,this.scrollTop,this.clientHeight)
      const condition = this.scrollHeight - this.scrollTop <= this.clientHeight + 1
      if (condition) {
        console.log(binding)
        binding.value && binding.value(binding.arg) // binding.value() 需要绑定函数  arg 传参
      }
    });
  },
  // 被绑定元素插入父节点时调用 (仅保证父节点存在，但不一定已被插入文档中)。
  inserted(el, binding, vNode) {

  },
  // 所在组件的 VNode 更新时调用，但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变，也可能没有
  update(el, binding, vNode) {

  },
  // 解绑时
  unbind(el, binding, vNode) {

  }
}
/*按钮 发请求 防抖*/
export const debounce = {
  bind(el, binding, vnode) {
    let timer = {}
    el.addEventListener('click', () => {
      if (timer) {
        clearTimeout(timer)
      }
      console.log(binding)
      timer = setTimeout(() => {
        binding.value(binding.arg)
        // binding.value() 需要绑定函数
      }, 2000)
    })

  },
}
/*输入框防抖*/
/**
 * <el-input style="width: 200px" v-model="inp" v-debounceInp="debounceChange"></el-input>  debounceChange 直接打印inp
 * */
export  const debounceInput = {
  bind(el, binding){
    // console.log(binding.arg)// 是否添加延迟的时间
    let delay = !!binding.arg ? binding.arg : 1000
    let timer = {}
    el.addEventListener('input', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        binding.value() //需要绑定函数
      }, delay)
    })
    // binding.value(binding.arg)
  },
  inserted(){

  },
  /*为什么 update 会重复执行*/
  update(el, binding, vnode) {

    /*     let timer = {}
         el.addEventListener('input', () => {
           if (timer) {
             clearTimeout(timer)
           }

           console.log(binding)
           console.log(binding.value.length)
           timer = setTimeout(() => {

             binding.value(binding.arg)
             clearTimeout(timer)
           }, 2000)
         })*/
  },
}

// throttle 输入框
export  const throttleInput = {
  inserted(el, binding) {
    let delay = !!binding.args ? binding.args : 1000
    let timer = null
    el.addEventListener('input', () => {
   /*   if (timer) {

      }
      timer = setTimeout(() => {
        binding.value() //需要绑定函数
        timer = null;
      }, delay)*/
      if(!timer) {
        timer = setTimeout(() => {
          binding.value()
          timer = null
        }, delay)
      }
      })
  }
}
// 权限指令
export  const permission = {
  inserted: function(el, binding) {
    const action = binding.value.action
    console.log("action",action)
    let userPrivilege =  JSON.parse(sessionStorage.getItem('userPrivilege')) || []
    const currentRight = userPrivilege.filter(item=> item.code==action)
    console.log("currentRight",currentRight)
    let right = currentRight[0]
    console.log("right",right)
    if (!!right) {
      // 不具备权限
      const type = right.privilege
      if (type == 'readOnly') {
        el.disabled = true
        el.classList.add('is-disabled')
      }else if(type == 'invisible'){
        el.parentNode.removeChild(el)
      }else{
        // 其他情况正常展示
      }

    }else{
      // 权限不存在直接移除
      el.parentNode.removeChild(el)
    }
  }
}



